package com.xmg.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baidu.aip.ocr.AipOcr;
import com.xmg.model.menu.*;
import com.xmg.service.WxService;
import org.json.JSONArray;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author xmg
 * @Description 微信工具类
 * @email 463364973@qq.com
 * <p>
 * Date:2019/4/5 15:33
 */
public class WxUtil {

    // 微信
    /** 公众号自定义token */
    public static final String TOKEN = "xmg";

    /** 自定义菜单微信服务器请求地址 */
    public static final String MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    // 阿里API 智能问答机器人
    /** 智能问答机器人 请求数据地址 */
    public static final String NLP_ASK_URL = "http://wenda2.market.alicloudapi.com/clouds/nlp/ask";
    /** 智能问答机器人 APP_CODE */
    public static final String NLP_APP_CODE = "你的code";

    // 百度AI设置APPID/AK/SK
    /** App ID */
    public static final String APP_ID = "你的appid";
    /** Api Key*/
    public static final String API_KEY = "你的apiKey";
    /** Secret Key*/
    public static final String SECRET_KEY = "你的secret";

    /**
     * 自定义菜单
     * @param args
     */
    public static void main(String[] args) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity request = new HttpEntity(createMenu(), headers);
        String url = MENU_URL.replace("ACCESS_TOKEN",WxService.getAccessToken());
        RestTemplate restTemplate = new RestTemplate();
        String s = restTemplate.postForObject(url, request, String.class);
        System.out.println("自定义菜单微信服务返回：--->" + s);
        //System.out.println(answerRobot("今天天气怎么样"));
    }

    /**
     * 创建自定义菜单
     * @return
     */
    public static String createMenu(){
        // 菜单对象
        Button button = new Button();
        // 第一个一级菜单
        button.getButton().add(new ClickButton("一级点击", "1"));
        // 第二个一级菜单
        button.getButton().add(new ViewButton("一级跳转","https://psnail.com"));
        // 创建第三个一级菜单
        SubButton subButton = new SubButton("有子菜单");
        // 为第三个一级菜单增加子菜单
        subButton.getSub_button().add(new PhotoOrAlbumButton("传图","31"));
        subButton.getSub_button().add(new ClickButton("子菜单的点击","32"));
        subButton.getSub_button().add(new ViewButton("百度","https://baidu.com"));
        // 加入第三个一级菜单
        button.getButton().add(subButton);
        // 转为json
        JSONObject jsonObject = JSONUtil.parseObj(button);
        return jsonObject.toString();
    }


    /**
     * 智能问答机器人 返回数据
     * @param content
     * @return
     */
    public static String answerRobot(String content){
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization","APPCODE " + NLP_APP_CODE);
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Map<String, String> map = new HashMap<>(2);
        map.put("question",content);
        HttpEntity request = new HttpEntity(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        String s = restTemplate.postForObject(NLP_ASK_URL, request, String.class);
        JSONObject jsonObject = JSONUtil.parseObj(s);

        if ("0".equals(jsonObject.getStr("code"))){
            String data = jsonObject.getStr("data");
            JSONObject jsonObject1 = JSONUtil.parseObj(data);
            return jsonObject1.getStr("answer");
        }
        return jsonObject.getStr("message");
    }

    /**
     * 百度AI文字识别
     * @param url
     * @return
     */
    public static String BaiDuAiWord(String url){
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        //System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        org.json.JSONObject jsonObject = client.basicGeneralUrl(url, new HashMap<String, String>());
        JSONArray words_result = jsonObject.getJSONArray("words_result");
        Iterator<Object> iterator = words_result.iterator();
        StringBuilder sb = new StringBuilder();
        while (iterator.hasNext()){
            org.json.JSONObject object = (org.json.JSONObject) iterator.next();
            sb.append(object.getString("words")).append("\n");
        }
        System.out.println("百度AI返回数据：--->"+ jsonObject.toString());
        return sb.toString();
    }

    /**
     * 设置模板消息所属行业
     * @param accessToken
     * @return
     */
    public static String setTrade(String accessToken, Map<String,Object> map){
        String url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=" + accessToken;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        map.put("industry_id1","1");
        map.put("industry_id2","2");
        HttpEntity request = new HttpEntity(map, headers);
        RestTemplate restTemplate = new RestTemplate();
        String s = restTemplate.postForObject(url, request, String.class);
        return s;
    }

    /**
     * 获取设置的行业信息
     * @return
     */
    public static String getTrade(String accessToken){
        String url = "https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=" + accessToken;
        RestTemplate restTemplate = new RestTemplate();
        String s = restTemplate.getForObject(url, String.class);
        return s;
    }

    /**
     * 发送模板
     * @param accessToken
     * @param data
     * @return
     */
    public static String sendTemplateMessage(String accessToken, String data){
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity request = new HttpEntity(data, headers);
        RestTemplate restTemplate = new RestTemplate();
        String s = restTemplate.postForObject(url, request, String.class);
        return s;
    }

    /**
     * 上传临时素材
     * @param path
     * @param type
     * @return
     */
    public static String upload(String path, String type) throws Exception {
        File file = new File(path);
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
        url = url.replace("ACCESS_TOKEN",WxService.getAccessToken()).replace("TYPE",type);

        // 请求内容
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        byte[] bytesArray = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        //read file into bytes[]
        fis.read(bytesArray);
        fis.close();
        ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {
            @Override
            public String getFilename() {
                return "img";
            }
        };
        param.add("media", contentsAsResource);
        //HttpEntity request = new HttpEntity(param, headers);
        RestTemplate restTemplate = new RestTemplate();
        String s = restTemplate.postForObject(url, param, String.class);
        return s;
    }

    /**
     * 获取去用户列表信息
     * @param nextOpenid
     * @return
     */
    public static String getUserList(String nextOpenid){
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID";
        url = url.replace("ACCESS_TOKEN",WxService.getAccessToken()).replace("NEXT_OPENID",nextOpenid);
        RestTemplate restTemplate = new RestTemplate();
        String result= restTemplate.getForObject(url,String.class);
        return result;
    }

    /**
     * 测试发送模板
     * @return
     */
    public static String testData(String openId){
        return "{\n" +
                "           \"touser\":\""+openId+"\",\n" +
                "           \"template_id\":\"0a0Qau4C796xMEcczE0ial2-H78KgDDmSFSdjT58tR0\",\n" +
                "           \"data\":{\n" +
                "                   \"first\": {\n" +
                "                       \"value\":\"您好，您的签到已被确认。\",\n" +
                "                       \"color\":\"#FF0000\"\n" +
                "                   },\n" +
                "                   \"keyword1\":{\n" +
                "                       \"value\":\"全栈开发工程师\",\n" +
                "                       \"color\":\"#BF3EFF\"\n" +
                "                   },\n" +
                "                   \"keyword2\": {\n" +
                "                       \"value\":\"云谷国际B座\",\n" +
                "                       \"color\":\"#141414\"\n" +
                "                   },\n" +
                "                   \"keyword3\": {\n" +
                "                       \"value\":\"2019-04-06 15:35:12\",\n" +
                "                       \"color\":\"#76EE00\"\n" +
                "                   },\n" +
                "                   \"keyword4\": {\n" +
                "                       \"value\":\"2019-04-06 15:35:12\",\n" +
                "                       \"color\":\"#7171C6\"\n" +
                "                   },\n" +
                "                   \"remark\":{\n" +
                "                       \"value\":\"快去工作吧，少年。\",\n" +
                "                       \"color\":\"#EE0000\"\n" +
                "                   }\n" +
                "           }\n" +
                "       }";
    }
}
